package com.lungle.warmdiary.app.view.active.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.nostra13.universalimageloader.core.ImageLoader;
import com.lungle.warmdiary.R;
import com.lungle.warmdiary.app.AppContext;
import com.lungle.warmdiary.app.api.HttpHelper;
import com.lungle.warmdiary.app.api.remote.ApiFactory;
import com.lungle.warmdiary.app.base.BaseFragment;
import com.lungle.warmdiary.app.base.BaseSubscriber;
import com.lungle.warmdiary.app.model.Result;
import com.lungle.warmdiary.app.model.request.ActiveExecuteUpdatePost;
import com.lungle.warmdiary.app.model.response.Active;
import com.lungle.warmdiary.app.model.response.Image;
import com.lungle.warmdiary.app.utils.DateUtil;
import com.lungle.warmdiary.app.utils.LoadLocalImageUtil;
import com.lungle.warmdiary.app.utils.StringUtils;
import com.umeng.analytics.MobclickAgent;

import java.io.File;
import java.util.ArrayList;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import me.iwf.photopicker.PhotoPicker;
import me.iwf.photopicker.PhotoPreview;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;


public class ExcuteScreenShotFragment extends BaseFragment {
    private static final String EXECUTE_SCREENSHOT_SCREEN = "execute screenshot screen";
    private final int CODE_SELECT = 1;
    private final int CODE_SHOW = 2;
    @Bind(R.id.iv_select)
    ImageView mIvSelect;
    private ArrayList<String> mImages = new ArrayList<>();
    private Active mActive;

    private boolean isUpload = true;
//    private ImagePreview mImagePreview;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_execute_screenshot, container, false);
        initData();
        initView(view);
        return view;
    }

    @Override
    public void initData() {
        mActive = (Active) getArguments().getSerializable("active");
        //在执行区间结束2小时后不可上传仅能查看结果，上传一张执行图片
        if (DateUtil.getHours(HttpHelper.getServerTime(), DateUtil.getDate(mActive.getEndtime())) < 2) {
            isUpload = true;
        } else {
            isUpload = false;
        }

    }

    @Override
    public void initView(View view) {
        ButterKnife.bind(this, view);
        if (mActive.getPublishScreenshot() != null) {
            ImageLoader.getInstance().displayImage(StringUtils.getPreviewImageUrl(mActive.getPublishScreenshot()), mIvSelect);
        }

//        mImagePreview = new ImagePreview(getActivity());

    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        if (isUpload) {
            getActivity().getMenuInflater().inflate(R.menu.active_detail, menu);
            menu.findItem(R.id.login_menu_send);
        }

    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (isUpload) {
            Observable.from(mImages).subscribe(s -> {
                uploadAndUpdate(new File(s));
            });
        } else {
            AppContext.showToastShort("当前活动不可以操作");
        }

        return true;
    }

    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart(EXECUTE_SCREENSHOT_SCREEN);
        MobclickAgent.onResume(getActivity());

    }

    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(EXECUTE_SCREENSHOT_SCREEN);
        MobclickAgent.onPause(getActivity());

    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }


    @OnClick(R.id.iv_select)
    public void onClick(View view) {
        if (!isUpload) {
            if (TextUtils.isEmpty(mActive.getPublishScreenshot())) return;


            ArrayList<String> arrayList = new ArrayList<>(1);
            arrayList.add(mActive.getPublishScreenshot());
            PhotoPreview.builder()
                    .setPhotos(arrayList)
                    .setCurrentItem(0)
                    .setShowDeleteButton(true)
                    .start(getActivity(), this, CODE_SHOW);
//            mImagePreview.showPreview(view, mActive.getPublishScreenshot());
            return;
        }

        PhotoPicker.builder()
                .setPhotoCount(1)
                .setShowCamera(false)
                .setShowGif(true)
                .setPreviewEnabled(false)
                .start(getActivity(), this, CODE_SELECT);
//        PhotoPickerIntent intent = new PhotoPickerIntent(getActivity());
//        intent.setPhotoCount(1);
//        intent.setShowCamera(false);
//        startActivityForResult(intent, CODE_SELECT);

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null && requestCode == CODE_SELECT) {
            mImages.addAll(data.getStringArrayListExtra(PhotoPicker.KEY_SELECTED_PHOTOS));
            if (mImages.size() > 0) {
                display(mImages.get(0));
            }
        }
    }


    private void display(String uri) {
        LoadLocalImageUtil.getInstance().displayFromSDCard(uri, mIvSelect);

    }

    private void uploadAndUpdate(File file) {
        showWaitDialog("正在上传...");
        RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
        MultipartBody.Part body = MultipartBody.Part.createFormData("file", file.getName(), requestFile);
        ApiFactory.getFileApi().upload(body).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<Result<Image>>(getActivity()) {
                    @Override
                    public void onCompleted() {
                        hideWaitDialog();
                        updateActiveState();
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        AppContext.showToast(e.getMessage());
                        hideWaitDialog();
                    }

                    @Override
                    public void onNext(Result<Image> result) {
                        mActive.setPublishScreenshot(result.getData().getUrl());

                    }
                });
    }


    private void setResultData() {
        if (getActivity() == null) return;
        Intent intent = new Intent();
        intent.putExtra(ActiveDetailFragment.ARGS_RESPONSE, mActive);
        getActivity().setResult(ActiveDetailFragment.CODE_REPONSE_EXECUTE, intent);
        getActivity().finish();
    }


    private void updateActiveState() {
        showWaitDialog("正在更新...");
        ActiveExecuteUpdatePost.CampaignProcess campaignProcess = new ActiveExecuteUpdatePost.CampaignProcess(mActive.getPublishScreenshot());
        ActiveExecuteUpdatePost post = new ActiveExecuteUpdatePost(campaignProcess);
        ApiFactory.getUserApi().updateActiveState(mActive.getId(), mActive.getMediaid(), post).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<Result>(getActivity()) {
                    @Override
                    public void onCompleted() {
                        hideWaitDialog();
                        setResultData();
                    }

                    @Override
                    public void onError(Throwable e) {
                        hideWaitDialog();
                        AppContext.showToast(e.getMessage());

                    }

                    @Override
                    public void onNext(Result result) {
                        AppContext.showToast("更新成功");
                    }
                });
    }


}
